
from django.http import HttpResponse, HttpResponseBadRequest, JsonResponse
from utils.normal_simple_function import serialize_json_dumps, serialize_json_date_type
from common.sql_instance_execute import *
from common.sql_constant_enum import *
from utils.cursorHandler import cursor
import json
import asyncio


async def caseStatistics_old(request):
    if request.method == 'POST':
        params_body: json = request.body
        params: dict = json.loads(params_body.decode())
        print('-----------', params)
        tag_type = params.get('tag_type', None)
        case_type = params.get('case_type', None)
        case_status = params.get('case_status', None)
        subsystem = params.get('subsystem', None)
        milestone_version = params.get('milestone_version', None)
        verison_NO = params.get('verison_NO', None)
        tester_name = params.get('tester_name', None)
        date_range = params.get('date_range', None)
        # 数据类型
        data_type = params.get('data_type', None)
        # case 条件查询的数据结果
        case_condition_search_result = []
        # 按照数据类型分类
        # data_type: 0 "用例创建总数"
        if data_type == 0:
            pass
        # data_type: 1 "用例执行总数"
        elif data_type == 1:
            pass
        # data_type: 2 "用例执行结果"
        elif data_type == 2:
            print(construct_sql_case_statistics_detail(case_tag_type_name_type[tag_type][1], case_status, subsystem, milestone_version, verison_NO, tester_name, date_range))
            case_condition_search_result = cursor.search_alone(
                construct_sql_case_statistics_detail(_tag_type=case_tag_type_name_type[tag_type][1],
                                                     _case_type=case_status,
                                                     _subsystem=subsystem,
                                                     _milestone_version=milestone_version,
                                                     _verison_NO=verison_NO,
                                                     _tester_name=tester_name,
                                                     _date_range=date_range))
        print(case_condition_search_result[:5])
        # 返回数据结构构造
        json_returns = {
            'data': {
                "case_total": len(case_condition_search_result),  # case总数
                "tag_type": tag_type,  # 标签类型
                "case_type": case_type,  # 数据类型
                "subsystem": subsystem,  # 子系统条件
                "milestone_version": milestone_version,  # 版本类型
                "verison_NO": verison_NO,  # 版本号
                "tester_name": tester_name,  # 姓名
                "date_range": date_range,  # 时间
                # case详情清单
                "case_detail_list": [{
                    # caseId
                    "case_id": each_case.get('case_id'),
                    # case标题
                    "case_title": each_case.get('title'),
                    # case状态
                    "case_status": each_case.get('status'),
                    # case优先级
                    "case_priority": each_case.get('priority'),
                    # 创建人
                    "creator": each_case.get('creator'),
                    # 创建时间
                    "create_date": serialize_json_date_type(each_case.get('create_date')),
                    # 解决方案
                    "solve_situation": each_case.get('resolution')
                } for each_case in case_condition_search_result if each_case]
            }
        }
        return HttpResponse(serialize_json_dumps(json_returns), content_type="application/json")
    else:
        return HttpResponseBadRequest(content=b'request is a bad request')


async def caseStatistics(request):
    if request.method == 'POST':
        params_body: json = request.body
        params: dict = json.loads(params_body.decode())
        print('-----------', params)
        # 项目id
        project_id = params.get('project_id', None)
        # 子系统id
        subsys_id = params.get('subsys_id', None)
        # 测试单id
        test_sheet_id = params.get('test_sheet_id', None)
        # case创建人
        creator_name = params.get('creator_name', None)
        # 执行人
        executor_name = params.get('executor_name', None)
        # 执行结果
        execute_result = params.get('execute_result', None)
        # 执行起始日期
        date_execute_start = params.get('date_execute_start', None)
        # 执行截止日期
        date_execute_end = params.get('date_execute_end', None)
        # 用例状态
        case_status = params.get('case_status', None)
        case_status = case_status if type(case_status) is str else case_status[0]
        # 用例类型
        case_type = params.get('case_type', None)
        case_type = case_type if type(case_type) is str else case_type[0]
        print('=============>', case_type)
        # 页码
        pageNo = params.get('pageNo', 0)
        # 页码显示数量
        pageNum = params.get('pageNum', 25)

        # case 条件查询的数据结果
        case_condition_search_result = []
        # 按照数据类型分类
        case_extension_sql = construct_sql_case_statistics_detail(
                                        _project_id=project_id,
                                        _subsys_id=subsys_id,
                                        _test_sheet_id=test_sheet_id,
                                        _creator_name=creator_name,
                                        _executor_name=executor_name,
                                        _execute_result=case_execute_result_constant_responding_Chinese.get(execute_result),
                                        _case_status=case_status_constant_responding_Chinese.get(case_status),
                                        _case_type=case_type_constant_responding_Chinese.get(case_type),
                                        _date_execute_start=date_execute_start,
                                        _date_execute_end=date_execute_end,
                                        _pageNum=pageNum,
                                        _pageNo=pageNo)
        case_extension_total_sql = construct_sql_case_statistics_all_sql_detail(
            _project_id=project_id,
            _subsys_id=subsys_id,
            _test_sheet_id=test_sheet_id,
            _creator_name=creator_name,
            _executor_name=executor_name,
            _case_status=case_status_constant_responding_Chinese.get(case_status),
            _case_type=case_type_constant_responding_Chinese.get(case_type),
            _execute_result=case_execute_result_constant_responding_Chinese.get(execute_result),
            _date_execute_start=date_execute_start,
            _date_execute_end=date_execute_end
        )
        print('查询数据结果', case_extension_sql)
        print('统计结果', case_extension_total_sql)
        case_condition_search_result = cursor.search_alone(case_extension_sql)
        case_total = cursor.search_alone(case_extension_total_sql)[0].get('total')
        print('输出3个数据作为样式', case_condition_search_result[:3])

        # 判断执行人，项目，子系统，执行起始时间，执行终止时间，有一个不为空，则统计用例总数与执行总数
        execute_case_total = -1
        execute_times_total = -1
        if executor_name or project_id or test_sheet_id or subsys_id or \
                date_execute_start or date_execute_end:
            # 执行用例总数
            case_execute_all_sql = construct_sql_execute_case_statistics_all(
                _project_id=project_id,
                _subsys_id=subsys_id,
                _test_sheet_id=test_sheet_id,
                _executor_name=executor_name,
                _date_execute_start=date_execute_start,
                _date_execute_end=date_execute_end,
                _case_status=case_status_constant_responding_Chinese.get(case_status),
                _case_type=case_type_constant_responding_Chinese.get(case_type),
            )
            print(case_execute_all_sql)
            execute_case_total = cursor.search_alone(case_execute_all_sql)[0].get('total')
            # 执行总次数
            execute_times_all_sql = construct_sql_execute_times_statistics_all(
                _project_id=project_id,
                _subsys_id=subsys_id,
                _test_sheet_id=test_sheet_id,
                _executor_name=executor_name,
                _date_execute_start=date_execute_start,
                _date_execute_end=date_execute_end,
                _case_status=case_status_constant_responding_Chinese.get(case_status),
                _case_type=case_type_constant_responding_Chinese.get(case_type),
            )
            print(execute_times_all_sql)
            execute_times_total = cursor.search_alone(execute_times_all_sql)[0].get('total')

        json_returns = {
            'data': {
                # case总数
                "case_total": case_total,
                # 执行用例总数
                "execute_case_total": execute_case_total,
                # 执行总次数
                "execute_times_total": execute_times_total,
                # 项目id
                "project_id" : project_id,
                # 子系统id
                "subsys_id" : subsys_id,
                # 测试单id
                "test_sheet_id" : test_sheet_id,
                # case创建人
                "creator_name" : creator_name,
                # 执行人
                "executor_name" : executor_name,
                # 执行结果
                "execute_result" : execute_result,
                # 执行起始日期
                "date_execute_start" : date_execute_start,
                # 执行截止日期
                "date_execute_end" : date_execute_end,
                # 用例状态
                "case_status" : case_status,
                # 用例类型
                "case_type" : case_type,
                # case详情清单
                "case_detail_list": [{
                    # projectId
                    "project_id": each_case.get('project_id'),
                    # subsysId
                    "subsys_id": each_case.get('subsys_id'),
                    # 测试单id
                    "test_sheet_id":each_case.get('task_id'),
                    # 项目名称
                    "pject_name": each_case.get('pject_name'),
                    # 子系统名称
                    "subsys_name": each_case.get('subsys_name'),
                    # 测试单名称
                    "task_name": each_case.get('task_name'),
                    # caseId
                    "case_id": each_case.get('case_id'),
                    # case优先级
                    "case_priority": each_case.get('priority'),
                    # case标题
                    "case_title": each_case.get('title'),
                    # case状态
                    "case_status": case_status_constant_responding_English.get(each_case.get('status')),
                    # case类型
                    "case_type": case_type_constant_responding_English.get(each_case.get('case_type')),
                    # 创建人
                    "creator": each_case.get('creator'),
                    # 执行人
                    "executor": each_case.get('executor'),
                    # 执行结果
                    "last_run_result": case_execute_result_constant_responding_English.get(each_case.get('last_run_result')),
                    # 创建时间
                    "create_date": serialize_json_date_type(each_case.get('create_date')),
                    # 执行时间
                    "execute_date": serialize_json_date_type(each_case.get('execute_date')),
                    # 执行次数
                    "execute_num": each_case.get('execute_num')
                } for each_case in case_condition_search_result if each_case]
            }
        }

        # 返回数据结构构造
        return HttpResponse(serialize_json_dumps(json_returns), content_type="application/json")
    else:
        return HttpResponseBadRequest(content=b'request is a bad request')




async def testerNameList(request):
    if request.method == 'GET':
        # 获取get请求带的参数
        # date_range = int(request.GET.get('date_range', 7))
        # 查询测试人员名单
        tester_name_list = cursor.search_alone(case_tester_name_list_sql)
        print(tester_name_list)

        json_returns = {
            'data': {
                "tester_names": tester_name_list,
                'total': len(tester_name_list)
            }
        }
        response =  HttpResponse(serialize_json_dumps(json_returns), content_type="application/json")
        return response
    else:
        return HttpResponseBadRequest(content=b'request is a bad request')


async def verisonNOList(request):
    if request.method == 'GET':
        # 获取get请求带的参数
        subsys_id = int(request.GET.get('subsys_id', 0))
        # 对传参做判断与分类
        if subsys_id:
            version_sql = construct_sql_case_version_by_subsys_search_sql(
                _subsys_id=subsys_id
            )
        elif subsys_id == 0 or not subsys_id:
            version_sql = construct_sql_case_version_by_subsys_search_sql()

        print(f'【case】version_sql: {version_sql}')
        # 查询测试人员名单
        version_name_list = cursor.search_alone(version_sql)
        print(f'【case】version_NO查询结果: {version_name_list}')
        json_returns = {
            'data': {
                "version_names": version_name_list,
                'total': len(version_name_list)
            }
        }
        response = HttpResponse(serialize_json_dumps(json_returns), content_type="application/json")
        return response
    else:
        return HttpResponseBadRequest(content=b'request is a bad request')


async def subsysList(request):
    if request.method == 'GET':
        # 获取get请求带的参数
        project_id = int(request.GET.get('project_id', 0))
        # 对传参做判断与分类
        if project_id:
            subsys_sql = construct_sql_case_subsys_by_project_search_sql(
                _project_id=project_id
            )
        elif project_id == 0 or not project_id:
            subsys_sql = construct_sql_case_subsys_by_project_search_sql()
        print(f'【case】subsys_sql: {subsys_sql}')
        # 查询测试人员名单
        subsys_list = cursor.search_alone(subsys_sql)
        # print(f'【case】subsys 列表的查询结果: {subsys_list}')
        json_returns = {
            'data': {
                "subsys_names": subsys_list,
                'total': len(subsys_list)
            }
        }
        response = HttpResponse(serialize_json_dumps(json_returns), content_type="application/json")
        return response
    else:
        return HttpResponseBadRequest(content=b'request is a bad request')


async def projectList(request):
    if request.method == 'GET':
        # 获取get请求带的参数
        # subsys_id = int(request.GET.get('subsys_id', 0))

        print(f'【Bug】version_sql: {case_all_project_name_list_sql}')
        # 查询测试人员名单
        project_list = cursor.search_alone(case_all_project_name_list_sql)
        # 这里是为了查询没有关联项目的人员
        project_list.insert(0,
            {'id': -1, 'name': ' ', 'status': ' '}
        )
        # print(f'【execute】project 列表的查询结果: {project_list}')
        json_returns = {
            'data': {
                "project_names": project_list,
                'total': len(project_list)
            }
        }
        response = HttpResponse(serialize_json_dumps(json_returns), content_type="application/json")
        return response
    else:
        return HttpResponseBadRequest(content=b'request is a bad request')


async def creatorList(request):
    if request.method == 'GET':
        # 获取get请求带的参数
        # date_range = int(request.GET.get('date_range', 7))
        # 查询测试人员名单
        tester_name_list = cursor.search_alone(case_tester_name_list_sql)
        print(tester_name_list)

        json_returns = {
            'data': {
                "tester_names": tester_name_list,
                'total': len(tester_name_list)
            }
        }
        response =  HttpResponse(serialize_json_dumps(json_returns), content_type="application/json")
        return response
    else:
        return HttpResponseBadRequest(content=b'request is a bad request')


async def executorList(request):
    if request.method == 'GET':
        # 获取get请求带的参数
        # date_range = int(request.GET.get('date_range', 7))
        # 查询测试人员名单
        executor_name_list = cursor.search_alone(case_executor_name_list_sql)
        print(executor_name_list)

        json_returns = {
            'data': {
                "executor_names": executor_name_list,
                'total': len(executor_name_list)
            }
        }
        response =  HttpResponse(serialize_json_dumps(json_returns), content_type="application/json")
        return response
    else:
        return HttpResponseBadRequest(content=b'request is a bad request')



async def caseStatuslist(request):
    if request.method == 'GET':
        # 获取get请求带的参数
        # date_range = int(request.GET.get('date_range', 7))
        print(case_status_constant_list)

        json_returns = {
            'data': {
                "executor_names": case_status_constant_list,
                'total': len(case_status_constant_list)
            }
        }
        response =  HttpResponse(serialize_json_dumps(json_returns), content_type="application/json")
        return response
    else:
        return HttpResponseBadRequest(content=b'request is a bad request')


async def executeRestultList(request):
    if request.method == 'GET':
        # 获取get请求带的参数
        # date_range = int(request.GET.get('date_range', 7))
        print(case_execute_result_constant_list)

        json_returns = {
            'data': {
                "executor_names": case_execute_result_constant_list,
                'total': len(case_execute_result_constant_list)
            }
        }
        response =  HttpResponse(serialize_json_dumps(json_returns), content_type="application/json")
        return response
    else:
        return HttpResponseBadRequest(content=b'request is a bad request')



async def testSheetList(request):
    if request.method == 'GET':
        # 获取get请求带的参数
        project_id = int(request.GET.get('project_id', 0))
        subsys_id = int(request.GET.get('subsys_id', 0))
        # 对传参做判断与分类
        if project_id or subsys_id:
            test_sheet_sql = construct_sql_case_test_sheet_by_project_search_sql(
                _project_id=project_id,
                _subsys_id=subsys_id
            )
        elif project_id == 0 or not project_id:
            test_sheet_sql = construct_sql_case_test_sheet_by_project_search_sql()
        print(f'【case】test_sheet_sql: {test_sheet_sql}')
        # 查询测试单
        subsys_list = cursor.search_alone(test_sheet_sql)
        # print(f'【case】subsys 列表的查询结果: {subsys_list}')
        json_returns = {
            'data': {
                "subsys_names": subsys_list,
                'total': len(subsys_list)
            }
        }
        response = HttpResponse(serialize_json_dumps(json_returns), content_type="application/json")
        return response
    else:
        return HttpResponseBadRequest(content=b'request is a bad request')



async def executeDateShow(request):
    if request.method == 'POST':
        params_body: json = request.body
        params: dict = json.loads(params_body.decode())
        print('-----------', params)
        # 执行的创建起始时间
        date_execute_start = params.get('date_execute_start', None)
        # 执行的创建行截止日期
        date_execute_end = params.get('date_execute_end', None)
        # 用例类型
        case_type = params.get('case_type', None)
        # 执行人
        executor_name = params.get('executor_name', None)


        # case_execute_search_sql = construct_sql_case_execute_data_distribute_by_date(
        #     _date_execute_start=date_execute_start,
        #     _date_execute_end=date_execute_end
        # )
        case_execute_search_sql_all = construct_sql_case_execute_data_distribute_by_date_with_all(
            _date_execute_start=date_execute_start,
            _date_execute_end=date_execute_end,
            _executor_name=executor_name,
            _case_type=case_type_constant_responding_Chinese.get(case_type)
        )
        case_execute_search_sql_each = construct_sql_case_execute_data_distribute_by_date_with_each(
            _date_execute_start=date_execute_start,
            _date_execute_end=date_execute_end,
            _executor_name=executor_name,
            _case_type=case_type_constant_responding_Chinese.get(case_type)
        )
        print(case_execute_search_sql_each)
        # case_execute_search_result = cursor.search_alone(case_execute_search_sql)
        case_execute_search_result_all = cursor.search_alone(case_execute_search_sql_all)
        case_execute_search_result_each = cursor.search_alone(case_execute_search_sql_each)
        all_case_execute_output_result = list(case_execute_search_result_all) + list(case_execute_search_result_each)


        json_returns = {
            'data': {
                "date_execute_start": date_execute_start, # Bug创建起始时间
                "date_execute_end": date_execute_end, # Bug创建行截止日期
                "execute_detail_list": [{
                    # 执行人
                    "executor": each_execute.get('executor'),
                    # 数据分布列表
                    "data_distribute": [
                        {
                            # 日期
                            "date": str(day_index),
                            # 对应的执行数量
                            "num": each_execute.get(str(day_index))} for day_index in range(1, 32)
                    ],
                    # 执行总数
                    "total": each_execute.get('total')
                } for each_execute in all_case_execute_output_result if each_execute]
            }
        }
        # 返回数据结构的构造
        return HttpResponse(serialize_json_dumps(json_returns), content_type="application/json")
    else:
        return HttpResponseBadRequest(content=b'request is a bad request')


async def executeTimeSlotShow(request):
    if request.method == 'POST':
        params_body: json = request.body
        params: dict = json.loads(params_body.decode())
        # print('-----------', params)
        # 执行的创建起始时间
        date_execute_start = params.get('date_execute_start', None)
        # 执行的创建行截止日期
        date_execute_end = params.get('date_execute_end', None)
        # 用例类型
        case_type = params.get('case_type', None)
        # 执行人
        executor_name = params.get('executor_name', None)

        # case_execute_search_sql = construct_sql_case_execute_data_distribute_by_time_slot(
        #     _date_execute_start=date_execute_start,
        #     _date_execute_end=date_execute_end
        # )
        case_execute_search_sql_all = construct_sql_case_execute_data_distribute_by_time_slot_with_all(
            _date_execute_start=date_execute_start,
            _date_execute_end=date_execute_end,
            _executor_name=executor_name,
            _case_type=case_type_constant_responding_Chinese.get(case_type)
        )
        case_execute_search_sql_each = construct_sql_case_execute_data_distribute_by_time_slot_with_each(
            _date_execute_start=date_execute_start,
            _date_execute_end=date_execute_end,
            _executor_name=executor_name,
            _case_type=case_type_constant_responding_Chinese.get(case_type)
        )
        print(case_execute_search_sql_each)
        # case_execute_search_result = cursor.search_alone(case_execute_search_sql)
        case_execute_search_result_all = cursor.search_alone(case_execute_search_sql_all)
        case_execute_search_result_each = cursor.search_alone(case_execute_search_sql_each)
        all_case_execute_output_result = list(case_execute_search_result_all) + list(case_execute_search_result_each)

        json_returns = {
            'data': {
                "date_execute_start": date_execute_start,  # Bug创建起始时间
                "date_execute_end": date_execute_end,  # Bug创建行截止日期
                "execute_detail_list": [{
                    # 执行人
                    "executor": each_execute.get('executor'),
                    # 数据分布列表
                    "data_distribute": [
                        {
                            # 时间段
                            "timeSlot": f"{time_slot}:{'0' if time_slot < 13 else '3'}0 ~ {time_slot + 1 if time_slot < 22 else 8}:{'0' if time_slot + 1 < 13 or time_slot == 22 else '3'}0",
                            # 对应的执行数量
                            "num": each_execute.get("+" + str(time_slot))} for time_slot in range(8, 23)
                    ],
                    # 执行总数
                    "total": each_execute.get('total')
                } for each_execute in all_case_execute_output_result if each_execute]
            }
        }
        # 返回数据结构的构造
        return HttpResponse(serialize_json_dumps(json_returns), content_type="application/json")
    else:
        return HttpResponseBadRequest(content=b'request is a bad request')



async def createDateShow(request):
    if request.method == 'POST':
        params_body: json = request.body
        params: dict = json.loads(params_body.decode())
        # print('-----------', params)
        # 执行的创建起始时间
        date_create_start = params.get('date_create_start', None)
        # 执行的创建行截止日期
        date_create_end = params.get('date_create_end', None)

        case_create_search_sql = construct_sql_case_create_data_distribute_by_week(
            _date_create_start=date_create_start,
            _date_create_end=date_create_end
        )
        print(case_create_search_sql)
        case_create_search_result = cursor.search_alone(case_create_search_sql)


        json_returns = {
            'data': {
                "date_create_start": date_create_start, # Bug创建起始时间
                "date_create_end": date_create_end, # Bug创建行截止日期
                    # 数据分布列表
                    "data_distribute": [
                        {
                            # case创建人
                            "creator": each_create.get('creator'),
                            # 工作日
                            "weekday": weekday_name_corresponding_Chinese.get(each_create.get('week_day'), "【总数】"),
                            # 周一
                            "Monday": each_create.get('Monday'),
                            # 周二
                            "Tuesday": each_create.get('Tuesday'),
                            # 周三
                            "Wednesday": each_create.get('Wednesday'),
                            # 周四
                            "Thursday": each_create.get('Thursday'),
                            # 周五
                            "Friday": each_create.get('Friday'),
                            # 周六
                            "Saturday": each_create.get('Saturday'),
                            # 周日
                            "Sunday": each_create.get('Sunday')
                        } for each_create in case_create_search_result if each_create]
                    }
                }
        # 返回数据结构的构造
        return HttpResponse(serialize_json_dumps(json_returns), content_type="application/json")
    else:
        return HttpResponseBadRequest(content=b'request is a bad request')


async def createDateShowByDate(request):
    if request.method == 'POST':
        params_body: json = request.body
        params: dict = json.loads(params_body.decode())
        # print('-----------', params)
        # 执行的创建起始时间
        date_create_start = params.get('date_create_start', None)
        # 执行的创建行截止日期
        date_create_end = params.get('date_create_end', None)
        # 创建人
        creator_name = params.get('creator_name', None)
        # case_create_search_sql = construct_sql_case_create_data_distribute_by_date(
        #     _date_create_start=date_create_start,
        #     _date_create_end=date_create_end
        # )
        case_create_search_sql = construct_sql_case_create_data_distribute_by_date_with_all(
            _date_create_start=date_create_start,
            _date_create_end=date_create_end,
            _creator_name=creator_name
        )
        case_create_search_sql = construct_sql_case_create_data_distribute_by_date_with_each(
            _date_create_start=date_create_start,
            _date_create_end=date_create_end,
            _creator_name=creator_name
        )
        print(case_create_search_sql)
        case_create_search_result = cursor.search_alone(case_create_search_sql)


        json_returns = {
            'data': {
                "date_create_start": date_create_start, # Bug创建起始时间
                "date_create_end": date_create_end, # Bug创建行截止日期
                    # 数据分布列表
                    "data_distribute": [
                        {
                            # case创建人
                            "creator": each_create.get('creator') if each_create.get('creator') is not None else "-不详-",
                            # 数据分布列表
                            "case_create_data_by_date": [
                                {"date": str(date),
                                 "num": each_create.get(str(date))
                                 } for date in range(1, 32)
                            ],
                            # 用例创建总数
                            "total": each_create.get('total')
                        } for each_create in case_create_search_result if each_create]
                    }
                }
        # 返回数据结构的构造
        return HttpResponse(serialize_json_dumps(json_returns), content_type="application/json")
    else:
        return HttpResponseBadRequest(content=b'request is a bad request')



async def caseTypeList(request):
    if request.method == 'GET':
        # 获取get请求带的参数
        # date_range = int(request.GET.get('date_range', 7))
        print(case_type_constant_list)

        json_returns = {
            'data': {
                "type_names": case_type_constant_list,
                'total': len(case_status_constant_list)
            }
        }
        response =  HttpResponse(serialize_json_dumps(json_returns), content_type="application/json")
        return response
    else:
        return HttpResponseBadRequest(content=b'request is a bad request')



























